package config

import (
	"notabug.org/apiote/next-eeze/crypto"
	"notabug.org/apiote/next-eeze/fido"
	"notabug.org/apiote/next-eeze/fs"

	"encoding/hex"
	"fmt"
	"os"

	"golang.org/x/crypto/ssh/terminal"
)

// todo memguard masterPassword
func Init(masterPassword string) {
	// todo memguard
	credentials := fs.Credentials{}
	fmt.Print("Server address: ")
	fmt.Scanf("%s", &credentials.Server)
	fmt.Print("Username: ")
	fmt.Scanf("%s", &credentials.Username)
	fmt.Print("Password: ")
	// todo memguard
	p_b, _ := terminal.ReadPassword(int(os.Stdin.Fd()))
	credentials.Password = string(p_b)
	fmt.Print("\n")

	fs.SaveCredentials(credentials, masterPassword)
}

func Reëncrypt(masterPassword string, useFido bool) (string, error) {
	newMasterPassword := ""
	err := fs.RemoveFidoCredential()
	if err != nil {
		fmt.Println(err)
		return "", err
	}
	if useFido {
		cdh := crypto.MakeSalt()
		salt := crypto.MakeSalt()
		credID := fido.Setup("next-eeze", "", cdh) // todo pin
		secret := fido.GetHmacSecret("next-eeze", "", cdh, salt, credID)
		newMasterPassword = hex.EncodeToString(secret)
		fs.SaveFidoCredential(fs.FidoCredential{
			Salt:   salt,
			Cdh:    cdh,
			CredID: credID,
		})
	} else {
		fmt.Print("New master password: ")
		// todo memguard
		p_b, _ := terminal.ReadPassword(int(os.Stdin.Fd()))
		newMasterPassword = string(p_b)
		fmt.Print("\n")
	}
	// todo memguard
	credentials, err := fs.ReadCredentials(masterPassword)
	if err != nil {
		return "", err
	}
	err = fs.SaveCredentials(credentials, newMasterPassword)
	if err != nil {
		return "", err
	}
	// todo memguard
	passwords, err := fs.Read(masterPassword)
	if err != nil {
		return "", err
	}
	err = fs.SaveBare(passwords, newMasterPassword)
	if err != nil {
		return "", err
	}

	return newMasterPassword, nil
}
